// 悬浮窗口内容脚本 - 注入到网页中的版本
class FloatingWindowInjector {
    constructor() {
        this.isInjected = false;
        this.floatingElement = null;
        this.isDragging = false;
        this.currentX = 0;
        this.currentY = 0;
        this.initialX = 0;
        this.initialY = 0;
        this.xOffset = 0;
        this.yOffset = 0;
        
        this.init();
    }

    init() {
        // 监听来自background的消息
        chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
            if (message.action === 'toggleFloatingWindow') {
                this.toggle();
                sendResponse({ success: true, isVisible: this.isInjected });
            } else if (message.action === 'closeFloatingWindow') {
                this.hide();
                sendResponse({ success: true });
            } else if (message.action === 'updateTasks') {
                this.updateTasks();
                sendResponse({ success: true });
            }
        });

        // 页面加载完成后初始化
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', () => this.setupStyles());
        } else {
            this.setupStyles();
        }
    }

    setupStyles() {
        // 添加悬浮窗口样式
        if (document.getElementById('wechatsync-float-styles')) return;

        const style = document.createElement('style');
        style.id = 'wechatsync-float-styles';
        style.textContent = `
            #wechatsync-floating-window {
                position: fixed !important;
                top: 20px;
                right: 20px;
                width: 400px;
                height: 500px;
                background: white !important;
                border-radius: 8px !important;
                box-shadow: 0 8px 32px rgba(0,0,0,0.3) !important;
                border: 1px solid #e0e0e0 !important;
                z-index: 2147483647 !important;
                font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif !important;
                overflow: hidden !important;
                transition: all 0.3s ease !important;
                backdrop-filter: blur(10px) !important;
            }

            #wechatsync-floating-window.minimized {
                height: 48px !important;
            }

            #wechatsync-floating-window.hidden {
                display: none !important;
            }

            .wechatsync-float-header {
                background: linear-gradient(135deg, #409EFF, #66b1ff) !important;
                color: white !important;
                padding: 12px 16px !important;
                display: flex !important;
                justify-content: space-between !important;
                align-items: center !important;
                cursor: move !important;
                user-select: none !important;
                border-bottom: 1px solid rgba(255,255,255,0.2) !important;
            }

            .wechatsync-float-title {
                font-size: 14px !important;
                font-weight: 500 !important;
                display: flex !important;
                align-items: center !important;
                gap: 8px !important;
            }

            .wechatsync-float-controls {
                display: flex !important;
                gap: 6px !important;
            }

            .wechatsync-float-btn {
                background: rgba(255,255,255,0.2) !important;
                border: none !important;
                color: white !important;
                width: 24px !important;
                height: 24px !important;
                border-radius: 4px !important;
                cursor: pointer !important;
                display: flex !important;
                align-items: center !important;
                justify-content: center !important;
                font-size: 12px !important;
                transition: all 0.2s ease !important;
            }

            .wechatsync-float-btn:hover {
                background: rgba(255,255,255,0.3) !important;
                transform: scale(1.1) !important;
            }

            .wechatsync-float-content {
                height: calc(100% - 48px) !important;
                overflow-y: auto !important;
                padding: 16px !important;
                background: #fafbfc !important;
            }

            .wechatsync-task-item {
                background: white !important;
                border-radius: 6px !important;
                padding: 12px !important;
                margin-bottom: 8px !important;
                border-left: 4px solid #409EFF !important;
                box-shadow: 0 2px 8px rgba(0,0,0,0.1) !important;
                transition: all 0.2s ease !important;
            }

            .wechatsync-task-item:hover {
                transform: translateY(-1px) !important;
                box-shadow: 0 4px 12px rgba(0,0,0,0.15) !important;
            }

            .wechatsync-task-title {
                font-size: 14px !important;
                font-weight: 500 !important;
                color: #303133 !important;
                margin-bottom: 4px !important;
            }

            .wechatsync-task-status {
                font-size: 12px !important;
                color: #909399 !important;
            }

            .wechatsync-empty-state {
                text-align: center !important;
                padding: 40px 20px !important;
                color: #909399 !important;
            }

            .wechatsync-empty-icon {
                font-size: 48px !important;
                margin-bottom: 16px !important;
                opacity: 0.5 !important;
            }

            .wechatsync-task-time {
                font-size: 11px !important;
                color: #c0c4cc !important;
                margin-top: 4px !important;
            }

            /* 滚动条样式 */
            .wechatsync-float-content::-webkit-scrollbar {
                width: 6px !important;
            }

            .wechatsync-float-content::-webkit-scrollbar-track {
                background: #f1f1f1 !important;
                border-radius: 3px !important;
            }

            .wechatsync-float-content::-webkit-scrollbar-thumb {
                background: #c1c1c1 !important;
                border-radius: 3px !important;
            }

            .wechatsync-float-content::-webkit-scrollbar-thumb:hover {
                background: #a8a8a8 !important;
            }
        `;
        document.head.appendChild(style);
    }

    createFloatingWindow() {
        if (this.floatingElement) return;

        const div = document.createElement('div');
        div.id = 'wechatsync-floating-window';
        div.className = 'hidden';
        
        div.innerHTML = `
            <div class="wechatsync-float-header" id="wechatsync-drag-handle">
                <div class="wechatsync-float-title">
                    <span>📝</span>
                    <span>微信同步助手</span>
                </div>
                <div class="wechatsync-float-controls">
                    <button class="wechatsync-float-btn" id="wechatsync-minimize-btn" title="最小化">−</button>
                    <button class="wechatsync-float-btn" id="wechatsync-close-btn" title="关闭">×</button>
                </div>
            </div>
            <div class="wechatsync-float-content" id="wechatsync-float-content">
                <div class="wechatsync-empty-state">
                    <div class="wechatsync-empty-icon">📋</div>
                    <div>暂无任务</div>
                </div>
            </div>
        `;

        document.body.appendChild(div);
        this.floatingElement = div;

        // 绑定事件
        this.bindEvents();
        
        // 加载任务数据
        this.updateTasks();
        
        // 定期更新
        setInterval(() => this.updateTasks(), 5000);
    }

    bindEvents() {
        const dragHandle = document.getElementById('wechatsync-drag-handle');
        const minimizeBtn = document.getElementById('wechatsync-minimize-btn');
        const closeBtn = document.getElementById('wechatsync-close-btn');

        // 拖拽事件
        dragHandle.addEventListener('mousedown', (e) => this.dragStart(e));
        document.addEventListener('mousemove', (e) => this.drag(e));
        document.addEventListener('mouseup', (e) => this.dragEnd(e));

        // 触摸事件
        dragHandle.addEventListener('touchstart', (e) => this.dragStart(e));
        document.addEventListener('touchmove', (e) => this.drag(e));
        document.addEventListener('touchend', (e) => this.dragEnd(e));

        // 控制按钮
        minimizeBtn.addEventListener('click', () => this.toggleMinimize());
        closeBtn.addEventListener('click', () => this.hide());
    }

    dragStart(e) {
        if (e.type === "touchstart") {
            this.initialX = e.touches[0].clientX - this.xOffset;
            this.initialY = e.touches[0].clientY - this.yOffset;
        } else {
            this.initialX = e.clientX - this.xOffset;
            this.initialY = e.clientY - this.yOffset;
        }

        if (e.target.id === 'wechatsync-drag-handle' || e.target.closest('#wechatsync-drag-handle')) {
            this.isDragging = true;
        }
    }

    drag(e) {
        if (this.isDragging) {
            e.preventDefault();
            
            if (e.type === "touchmove") {
                this.currentX = e.touches[0].clientX - this.initialX;
                this.currentY = e.touches[0].clientY - this.initialY;
            } else {
                this.currentX = e.clientX - this.initialX;
                this.currentY = e.clientY - this.initialY;
            }

            this.xOffset = this.currentX;
            this.yOffset = this.currentY;

            this.setTranslate(this.currentX, this.currentY);
        }
    }

    dragEnd(e) {
        this.initialX = this.currentX;
        this.initialY = this.currentY;
        this.isDragging = false;
    }

    setTranslate(xPos, yPos) {
        if (this.floatingElement) {
            this.floatingElement.style.transform = `translate3d(${xPos}px, ${yPos}px, 0)`;
        }
    }

    toggleMinimize() {
        if (this.floatingElement) {
            this.floatingElement.classList.toggle('minimized');
        }
    }

    toggle() {
        if (!this.floatingElement) {
            this.createFloatingWindow();
        }

        if (this.floatingElement.classList.contains('hidden')) {
            this.show();
        } else {
            this.hide();
        }
    }

    show() {
        if (this.floatingElement) {
            this.floatingElement.classList.remove('hidden');
            this.isInjected = true;
        }
    }

    hide() {
        if (this.floatingElement) {
            this.floatingElement.classList.add('hidden');
            this.isInjected = false;
        }
    }

    async updateTasks() {
        if (!this.floatingElement || this.floatingElement.classList.contains('hidden')) return;

        try {
            const response = await chrome.runtime.sendMessage({ action: 'getTasks' });
            const tasks = response || [];
            const content = document.getElementById('wechatsync-float-content');
            
            if (tasks.length === 0) {
                content.innerHTML = `
                    <div class="wechatsync-empty-state">
                        <div class="wechatsync-empty-icon">📋</div>
                        <div>暂无任务</div>
                    </div>
                `;
                return;
            }
            
            const tasksHtml = tasks.map(task => `
                <div class="wechatsync-task-item">
                    <div class="wechatsync-task-title">${this.escapeHtml(task.title || '未命名任务')}</div>
                    <div class="wechatsync-task-status">${this.getStatusText(task.status)}</div>
                    ${task.createdAt ? `<div class="wechatsync-task-time">${this.formatTime(task.createdAt)}</div>` : ''}
                </div>
            `).join('');
            
            content.innerHTML = tasksHtml;
        } catch (error) {
            console.log('更新任务失败:', error);
        }
    }

    escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }

    getStatusText(status) {
        const statusMap = {
            'pending': '等待中',
            'running': '同步中',
            'success': '同步成功',
            'failed': '同步失败'
        };
        return statusMap[status] || '未知状态';
    }

    formatTime(timestamp) {
        if (!timestamp) return '';
        const date = new Date(timestamp);
        return date.toLocaleString('zh-CN');
    }
}

// 初始化注入器
new FloatingWindowInjector();